

<!-- //文章编辑 -->
<template>
    <a-page-header class="site-page-header">
        <template #tags>
            <a-popconfirm title="你确定要退出吗？ 未保存的内容会丢失" ok-text="是" cancel-text="不" @confirm="confirm" @cancel="cancel">
                <a-tag color="blue">x</a-tag>
            </a-popconfirm>
            <input class="tit_ipt" type="text" v-model="titletval">
        </template>
        <template #extra>
            <a-button key="1" type="primary" @click="okok">发布</a-button>
            <a-dropdown key="more">
                <a-button>
                    <menu-fold-outlined />
                </a-button>
                <template #overlay>
                    <a-menu>
                        <a-menu-item>
                            <a :href="'https://creationapi.shbwyz.com/' + route.params.id" target="blank">查看</a>
                        </a-menu-item>
                        <a-menu-item @click="showDrawer">
                            设置
                        </a-menu-item>
                        <a-menu-item @click="okstatus">
                            保存草稿
                        </a-menu-item>
                        <a-menu-item>
                            删除
                        </a-menu-item>
                    </a-menu>
                </template>
            </a-dropdown>
        </template>
    </a-page-header>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
        <Editor style="height: 100vh; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
            @onCreated="handleCreated" />
    </div>

    <!-- 抽屉 -->
    <!-- 抽屉 -->
    <a-drawer v-model:visible="visible" class="custom-class" title="文章设置" placement="right" width="600"
        @after-visible-change="afterVisibleChange">
        <a-card style="width: 100%">
            <a-form name="customized_form_controls" layout="inline" style="margin: 30px 0; background: #fff"
                expandFixed="true">
                <!-- 文件名称输入框 -->
                <div class="form_item">
                    <a-form-item name="price" label="文章摘要">
                        <a-input v-model:value="summary" placeholder="请输入内容" />
                    </a-form-item>
                </div>
                <!-- 文件类型输入框 -->
                <div class="form_item">
                    <a-form-item name="price" label="访问密码">
                        <a-input v-model:value="password" placeholder="请输入密码" />
                    </a-form-item>
                </div>
                <!-- 文件类型输入框 -->
                <div class="form_item">
                    <a-form-item name="price_1" label="付费查看">
                        <a-input v-model:value="totalAmount" placeholder="请输入内容" />
                    </a-form-item>
                </div>
                <div class="form_item">
                    <a-form-item name="price_2" label="开启评论">
                        <a-switch v-model:checked="isCommentable" />
                    </a-form-item>
                </div>
                <div class="form_item">
                    <a-form-item name="price_3" label="首页推荐">
                        <a-switch v-model:checked="isRecommended" />
                    </a-form-item>
                </div>
                <div class="form_item">
                    <a-form-item name="price_4" label="选择分类">
                        <a-select v-model="categorys" style="width: 120px" :placeholder="categorys" @change="handleChange1">
                            <a-select-option v-for="(item, ind) in category" :key="ind" :value="item.label">{{ item.label
                            }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </div>
                <div class="form_item">
                    <a-form-item name="price_5" label="选择标签">
                        <a-select v-model:value="tagsall" mode="multiple" style="width: 100%" @change="handleChange2">
                            :options="tag.map((item: any, i: number) => ({ value: item.value }))"
                            <a-select-option v-for="(item, ind) in tag" :key="ind" :value="item.label">{{ item.label
                            }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </div>

                <!-- 封面 -->
                <div class="form_item">
                    <a-form-item label="封面">
                        <a-upload-dragger v-model:fileList="fileList" name="file" :multiple="true"
                            @change="handleChangefile" @drop="handleDrop" :customRequest="setfile" :showUploadList="false">
                            <div v-if="cover == ''">
                                <p class="ant-upload-text">点击选择文件或将文件拖拽到此处</p>
                                <p class="ant-upload-hint">文件将上传到OSS,如未配置请先配置</p>
                            </div>
                            <img v-else :src="cover" class="imgsa" alt="">
                        </a-upload-dragger>

                        <a-input v-model:value="cover" placeholder="请输入名称" />
                    </a-form-item>
                </div>
                <!-- 按钮 -->
                <div class="form_item">
                    <a-form-item>
                        <a-space>
                            <a-button @click="() => showDrawers()">选择文件</a-button>
                            <a-button @click="yichu">移除</a-button>
                        </a-space>
                    </a-form-item>
                </div>
                <a-form-item expandFixed="right">
                    <a-button type="primary" @click="asy">确认</a-button>
                </a-form-item>
            </a-form>
        </a-card>
    </a-drawer>
    <!-- 抽屉2.0 -->
    <a-drawer v-model:visible="visibles" class="custom-class" title="文件选择" placement="right" width="800"
        @after-visible-change="afterVisibleChanges">
        <a-card style="width: 100%">
            <!-- 搜索 -->
            <a-form name="customized_form_controls" layout="inline" :model="file_values" @finish="onFinishe"
                style="margin: 30px 0; background: #fff" expandFixed="true">
                <!-- 文件名称输入框 -->
                <a-form-item name="price" label="文件名称">
                    <a-input v-model:value="file_values.title" placeholder="请输入标题" />
                </a-form-item>
                <!-- 文件类型输入框 -->
                <a-form-item name="price" label="文件类型">
                    <a-input v-model:value="file_values.types" placeholder="请输入标题" />
                </a-form-item>
                <a-form-item expandFixed="right">
                    <a-button type="primary" html-type="submit">搜索</a-button>
                    <a-button @click="() => toset()">重置</a-button>
                </a-form-item>
            </a-form>
        </a-card>
        <br />
        <a-card style="width: 100%">
            <div class="imgs_box">
                <div v-for="(item, ind) in fileLists" :key="ind" @click="() => editurl(item.url)">
                    <img :src="item.url" alt="">
                    <p style="font-weight: bold;">{{ item.originalname }}</p>
                    <p style="font-size: 12px;">上传于：{{ item.createAt }}</p>
                </div>
            </div>
        </a-card>
        <a-card style="width: 100%">
            <a-pagination v-model:current="file_current" v-model:page-size="file_pageSize" :total="totals"
                :page-size-options="pageSizeOptionse" show-size-changer @showSizeChange="onShowSizeChangee"
                @change="pageChagee" />
        </a-card>

    </a-drawer>
</template>

<script setup lang="ts">
import { MenuFoldOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { ref, reactive, onBeforeUnmount, shallowRef, onMounted, watch, onUpdated } from "vue"
import { useRoute, useRouter } from "vue-router"
import { useHome } from "../../store/home";
import { useFiles } from "../../store/files"
import { storeToRefs } from "pinia"
//编辑器
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IDomEditor } from '@wangeditor/editor'
import { message } from 'ant-design-vue';
let route = useRoute()
let router = useRouter()
//初始化pinia
let homes = useHome()
let ufiles = useFiles()

let { cover, fileLists, totals } = storeToRefs(ufiles)
//初始化获取一下数据
homes.getSearchs({ page: 1, pageSize: 100 });
homes.gettag();
homes.getcategory();
let { imgs, tag, category } = storeToRefs(homes)
//标题
let titletval = ref("");
let item = {} as any;
let toc = ref("");
//文章摘要
let summary = ref(""),
    //访问密码
    password = ref(""),
    //付费查看
    totalAmount = ref(""),
    //开启评论
    isCommentable = ref(false),
    //首页推荐
    isRecommended = ref(false),
    //选择分类
    categorys = ref(""),
    //文章状态
    status = ref("publish"),
    //选择标签
    tagsall = ref([] as any);
//文章封面
// let cover = ref("");

//定义搜索框的初始数据
const file_values = reactive({
    title: "",
    types: ""
});
//重置
const toset = () => {
    location.reload()
}
const editurl = (val: any) => {
    cover.value = val
    visibles.value = false;
}
//上传
const setfile = (v: any) => {
    // console.log(v, "set file")
}
let fileList = ref([]),
    handleDrop = (e: DragEvent) => {
        console.log(e);
    };
const showDrawers = () => {
    visibles.value = true;
    //初始化页面数据
    localStorage.removeItem("searchobj")
};
const afterVisibleChanges = (bool: boolean) => {
    console.log('visible', bool);
};


//上传
const handleChangefile = async (info: any) => {
    console.log(info.file.originFileObj, "info")
    ufiles.uploadfile(info.file.originFileObj)

};
// 移除
const yichu = () => {
    cover.value = ""
}

const confirm = (e: MouseEvent) => {
    console.log(e);
    //   message.success('Click on Yes');
    router.push("/")
};

const cancel = (e: MouseEvent) => {
    console.log(e);
    message.error('Click on No');
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
let mode = 'default';
// 内容 HTML
let valueHtml = ref('')
let textVal = ref("");
let editor = null as any;

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }
// 初始化获取信息
// onMounted(()=>{
//     setTimeout(() => {
//         item = imgs.value.find((v: any) => v.id === route.params.id)
//         console.log(imgs,"imgs")
//         console.log(item,"imgs item")
//     }, 1500);
// })
item = imgs.value.find((v: any) => v.id === route.params.id)

//监听
watch(imgs,(newval)=>{
    item =[...newval].find((v: any) => v.id === route.params.id)
    console.log(newval,"进入页面 获取 imgs")
    console.log(item,"进入页面 获取 imgs")

      //标题
      titletval.value = item.title || ""
    //html
    valueHtml.value = item.html || ""
    //文章摘要
    summary.value = item.summary || ""
    //访问密码
    password.value = item.password || ""
    // 付费查看
    totalAmount.value = item.totalAmount || ""
    //开启评论
    isCommentable.value = item.isCommentable || false
    //首页推荐
    isRecommended.value = item.isRecommended || false
    //选择标签
    let arr = [] as any;
    if (item.tags.length > 0) {
        arr = item.tags.map((v: any) => v.label)
    }
    tagsall.value = arr || []
    //选择分类
    let categorystr = ""
    if (item.category) {
        categorystr = item.category.label
    }
    categorys.value = categorystr || ""
    //文章封面
    cover.value = item.cover || ""
})

onMounted(() => {
    editor = editorRef.value
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: any) => {// `content` 即为 JSON 内容
    const html = editor.getHtml()
    const text = editor.getText()
    editorRef.value = editor // 记录 editor 实例，重要！
}

//监听编辑器内容的改变
watch(valueHtml, (newval) => {
    let text = editorRef.value.getText()
    textVal.value = text
    let arr = [] as any;
    // console.log(editorRef.value, "values")
    if (editorRef.value) {
        editorRef.value.children.map((v: any) => {
            arr.push(v.children[0])
        })
        // console.log(JSON.stringify(arr), "toc")
        toc.value = JSON.stringify(arr)
    }
})

//抽屉
const visible = ref<boolean>(false);
const visibles = ref<boolean>(false);

//开启抽屉
const showDrawer = () => {
    visible.value = true;
};
const afterVisibleChange = (bool: boolean) => {
    console.log('visible', bool);
};
//分类
const handleChange1 = (val: any) => {
    console.log(val, "分类")
    // console.log(categorys,"handel1")
    categorys.value = val
}
//标签
const handleChange2 = (val: any) => {
    console.log(val, "标签")
}
//点击确定
const asy = () => {
    visible.value = false
}


let file_current = ref(1);
let file_pageSize = ref(8);
const pageSizeOptionse = ref<string[]>(['8', '12', '16', '20', '24']);

let file_flag = false;
//文件数据
let fileitem = {}
//初始化获取数据
ufiles.getsearchfiles({ page: file_current.value, pageSize: file_pageSize.value })
//切换分页条数
const onShowSizeChangee = (currents: number, pageSizes: number) => {
    console.log(currents, pageSizes, "页码，条数");
    file_current.value = 1
    file_pageSize.value = pageSizes;
};
//切换页数
const pageChagee = (page: number, pageSize: number) => {
    file_current.value = page;
    file_flag = false;
    searche()
}

//点击搜索获取表单数据
const onFinishe = () => {
    //点击模糊搜索
    console.log(file_values, "values")
    file_flag = true;
    searche()
}

//封装一个模糊搜索的方法
const searche = () => {
    let obj = {};
    if (file_flag) {
        file_current.value = 1,
            file_pageSize.value = 12
        obj = {
            page: file_current.value,
            pageSize: file_pageSize.value
        }
    } else {
        obj = JSON.parse(localStorage.getItem("searchobj") || "{}")
        obj = {
            ...obj,
            page: file_current.value,
            pageSize: file_pageSize.value
        }
    }
    if (file_values.title != "") {
        obj = { ...obj, originalname: file_values.title }
    }
    if (file_values.types != "") {
        obj = { ...obj, type: file_values.types }
    }

    ufiles.getsearchfiles(obj)
}
//点击发布
const okok = () => {

    let objs = {};
    console.log(item, "item")
    if (tagsall.value.length > 0) {
        let tagsa = [] as any;
        tag.value.map((v: any) => {
            console.log(v, "vvvvvvv")
            tagsall.value.map((i: any) => {
                if (v.label == i) {
                    tagsa.push(v.id)
                }
            })
        })
        objs = {
            tags: tagsa.join(",")
        }
    }
    console.log(categorys.value, "cates")
    if (categorys.value != "") {
        category.value.map((v: any) => {
            if (v.label == categorys.value) {
                objs = {
                    ...objs,
                    category: v.id
                }
            }
        })
    }

    if (item) {
        let id = item.id;
        objs = {
            ...item,
            ...objs,
            //标题
            titletval: titletval.value || "",
            //html
            html: valueHtml.value || "",
            //toc
            toc: toc.value || "",
            //content
            content: textVal.value || "",
            //文章摘要
            summary: summary.value || "",
            //访问密码
            password: password.value || "",
            // 付费查看
            totalAmount: totalAmount.value || "",
            //开启评论
            isCommentable: isCommentable.value || false,
            //首页推荐
            isRecommended: isRecommended.value || false,
            cover: cover.value || "",
            status: status.value || "publish",
        }
        homes.edittexts(id, objs)
    }


}
//保存草稿
const okstatus = () => {
    let objs = {};
    console.log(item, "item")
    if (tagsall.value.length > 0) {
        let tagsa = [] as any;
        tag.value.map((v: any) => {
            // console.log(v, "vvvvvvv")
            tagsall.value.map((i: any) => {
                if (v.label == i) {
                    tagsa.push(v.id)
                }
            })
        })
        objs = {
            tags: tagsa.join(",")
        }
    }
    // console.log(categorys.value, "cates")
    if (categorys.value != "") {
        category.value.map((v: any) => {
            if (v.label == categorys.value) {
                objs = {
                    ...objs,
                    category: v.id
                }
            }
        })
    }

    if (item) {
        let id = item.id;
        objs = {
            ...item,
            ...objs,
            //标题
            titletval: titletval.value || "",
            //html
            html: valueHtml.value || "",
            //toc
            toc: toc.value || "",
            //content
            content: textVal.value || "",
            //文章摘要
            summary: summary.value || "",
            //访问密码
            password: password.value || "",
            // 付费查看
            totalAmount: totalAmount.value || "",
            //开启评论
            isCommentable: isCommentable.value || false,
            //首页推荐
            isRecommended: isRecommended.value || false,
            cover: cover.value || "",
            status: "draft"
        }
        homes.edittexts(id, objs)
    }
}




</script>

<style lang="scss">
.tit_ipt {
    border-left: none;
    border-top: none;
    border-right: none;
    background: none;
    outline: none;

    &:hover {
        border-bottom: 1px solid skyblue;
    }
}
</style>